package cn.com.sinux.spring.utils;

import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/9/8.
 */
public class SpecificationHelper {


    public static interface SpecificationBuilder<T> {
        public void fillParam(Root<T> root, CriteriaBuilder cb, List<Predicate> list);
    }

    public static <T> Specification<T> buildSpecification(final SpecificationBuilder<T> specificationBuilder) {
         Specification specification = new Specification<T>() {
            public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                specificationBuilder.fillParam(root, cb, list);
                query.where(list.toArray(new Predicate[list.size()]));
                return query.getRestriction();
            }
        };
        return specification;
    }
}
